<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form style="height:97%;">
                    <div class="formSolution">
                        <a-form-item :labelCol1="6" :wrapperCol1="18" :label="i18n('btnPreConf.mode','模式')">
                            <a-radio-group v-model="mode" @change="change">
                                <a-radio value="easy">{{ i18n('btnPreConf.easy', '简易模式') }}</a-radio>
                                <a-radio value="hard">{{ i18n('btnPreConf.hard', '高级模式') }}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <div class="formSolution-center" :class="[mode=='easy'?'formSolution-center-flex':'']">
                            <div v-if="mode=='easy'" class="FormSolutionDefMappingConfig-easy">
                                <rx-condition-group ref="easyCondition" :ruleData="easyCondition"
                                                    :defaultRule="defaultRule" :level="2" :allowEmpty="true">
                                    <template slot="conditionDiv" slot-scope="{rule,setValid}">
                                        <div style="display:flex;">
                                            <div class="findSelectBox">
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18n('easyColumns.field', '字段')"
                                                          style="width: 100%"
                                                          v-model="rule.formField"
                                                          allowClear
                                                          @change="formFieldChange(rule.formField,rule,setValid)"
                                                          :options="formFields"/>
                                            </div>
                                            <div class="findSelectBox">
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18n('easyColumns.comparator', '比较符')"
                                                          v-if="rule.dataType=='number' || rule.dataType=='int'"
                                                          v-model="rule.op"
                                                          :options="numOptions"/>
                                                <a-select :getPopupContainer="p=>p.parentNode"
                                                          :placeholder="i18n('easyColumns.comparator', '比较符')"
                                                          v-else-if="rule.dataType=='date'" v-model="rule.op"
                                                          :options="dateOptions"/>
                                                <a-select :getPopupContainer="p=>p.parentNode" v-else
                                                          :placeholder="i18n('easyColumns.comparator', '比较符')"
                                                          v-model="rule.op"
                                                          :options="strOptions"/>
                                            </div>
                                            <div class="findInputBox" v-if="rule.op!='ISNULL' && rule.op!='NOTNULL'">
                                                <a-input-number v-if="rule.dataType=='number' || rule.dataType=='int'"
                                                                :min="0"
                                                                v-model="rule.conditionConfig"
                                                                :placeholder="i18n('easyColumns.condition', '条件')" />
                                                <a-date-picker v-else-if="rule.dataType=='date'"
                                                               format="YYYY-MM-DD"
                                                               value-format="YYYY-MM-DD"
                                                               v-model="rule.conditionConfig"
                                                               :getCalendarContainer="p=>p.parentNode"/>
                                                <a-input v-else
                                                         v-model="rule.conditionConfig"
                                                         :placeholder="i18n('easyColumns.condition', '条件')" />

                                            </div>
                                        </div>
                                    </template>
                                </rx-condition-group>
                            </div>
                            <div v-if="mode=='hard'" class="rx-monaco-editor-center" style="margin-right: 20px">
                                <a-alert
                                    :message="i18n('btnPreConf.buttonUse','满足以下条件，可以显示按钮')"
                                    :description="i18n('btnPreConf.enterJava','在下面代码编辑器输入JAVA代码作为按钮前置条件，rows：表示选中的行')"
                                    type="info"
                                    show-icon
                                />
                                <rx-monaco-editor ref="javaCode"
                                                  v-model="javaCode"
                                                  :key="mode"
                                                  style="margin-top: 10px"
                                                  language="java">
                                    <template v-slot:monacoeditor>
                                        <div style="display: flex;align-items: center">

                                            <div class="form-tree-certen">
                                                <a-button style="margin-right: 8px;width: 170px">
                                                    {{ i18n('btnPreConf.context', '上下文数据') }}
                                                    <a-icon type="down"/>
                                                </a-button>
                                                <div class="form-tree">
                                                    <a-tree
                                                        :multiple="false"
                                                        :show-icon="false"
                                                        :treeData="boData"
                                                        @select="selectBoNode"
                                                    ></a-tree>
                                                </div>
                                            </div>

                                            <span>
                                                <a-button icon="edit" @click="showScriptDialog()">
                                                    {{ i18n('list.quickScript', '快速脚本') }}
                                                </a-button>
                                            </span>
                                            <span style="padding-left: 5px">
                                                <rx-constant-field @select="insertConst"></rx-constant-field>
                                            </span>
                                            <rx-common-script @select="insertJavaCode" use-to="list-bolistBtn" type="1">
                                                <template v-slot:button>
                                                    <a-button style="margin-right: 8px">
                                                        {{ i18n('list.insertCode', '插入代码') }}
                                                        <a-icon type="down"/>
                                                    </a-button>
                                                </template>
                                            </rx-common-script>
                                        </div>
                                    </template>
                                </rx-monaco-editor>
                            </div>
                            <!--后置条件-->
                            <div class="rx-monaco-editor-center">
                                <a-alert
                                    :message="i18n('btnPreConf.promptMsg','不满足按钮前置条件时的提示信息')"
                                    :description="i18n('btnPreConf.promptJava','在下面代码编辑器输入JAVA代码作为不满足前置条件的错误提示，rows：表示选中的行')"
                                    type="info"
                                    show-icon
                                />
                                <rx-monaco-editor ref="validMsg"
                                                  v-model="validMsg"
                                                  :key="mode"
                                                  style="margin-top: 10px"
                                                  language="java">
                                    <template v-slot:monacoeditor>
                                        <div style="display: flex;align-items: center;height: 100%">
                                            <span style="padding-left: 5px">
                                                <rx-constant-field @select="insertMsgConst"></rx-constant-field></span>

                                            <rx-common-script @select="insertValidMsgCode" use-to="list-bolistBtn"
                                                              type="1">
                                                <template v-slot:button>
                                                    <a-button style="margin-right: 8px">
                                                        {{ i18n('list.insertCode', '插入代码') }}
                                                        <a-icon type="down"/>
                                                    </a-button>
                                                </template>
                                            </rx-common-script>
                                        </div>
                                    </template>
                                </rx-monaco-editor>

                            </div>
                        </div>
                    </div>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import {
  Dialog,
  RxCommonScript,
  RxConditionGroup,
  RxDialog,
  RxGrid,
  RxLayout,
  RxMonacoEditor,
  Util
} from "@lowcode/jpaas-common-lib";
import FormBoListApi from "@/api/form/core/formBoList";

export default {
    name: "FormBoListButtonPreConfig",
    components: {
        RxDialog,
        RxLayout,
        RxGrid,
        RxMonacoEditor,
        RxCommonScript,
        RxConditionGroup
    },
    props: ["layerid", "destroy", "config", "pkId", "fieldDatas"],
    data() {
        return {
            mode: "easy",
            formFields: [],
            boData: [{
                key: 'context',
                name: 'context',
                title: this.i18n('btnPreConf.context', '上下文数据'),
                isField: false,
                children: [
                    {key: 'curUserId', name: 'curUserId', title: this.i18n('btnPreConf.userId', '用户ID'), isField: true},
                    {
                        key: 'curUserName',
                        name: 'curUserName',
                        title: this.i18n('btnPreConf.userName', '用户名称'),
                        isField: true
                    },
                    {key: 'account', name: 'account', title: this.i18n('btnPreConf.account', '用户账号'), isField: true},
                    {key: 'deptId', name: 'deptId', title: this.i18n('btnPreConf.deptId', '用户主部门ID'), isField: true}
                ]
            }],
            javaCode: '',
            validMsg: '',
            strOptions: [
                {value: 'EQ', label: this.i18n('btnPreConf.equal', '等于')},
                {value: 'NEQ', label: this.i18n('btnPreConf.notEqual', '不等于')},
                {value: 'IN', label: this.i18n('btnPreConf.include', '包含')},
                {value: 'NIN', label: this.i18n('btnPreConf.notInclude', '不包含')},
                {value: 'ISNULL', label: this.i18n('btnPreConf.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('btnPreConf.notEmpty', '不为空')},
            ],
            numOptions: [
                {value: 'EQ', label: this.i18n('btnPreConf.equal', '等于')},
                {value: 'NEQ', label: this.i18n('btnPreConf.notEqual', '不等于')},
                {value: 'LT', label: this.i18n('btnPreConf.lessThan', '小于')},
                {value: 'LE', label: this.i18n('btnPreConf.lessOrEqual', '小于等于')},
                {value: 'GT', label: this.i18n('btnPreConf.greater', '大于')},
                {value: 'GE', label: this.i18n('btnPreConf.greatOrEqual', '大于等于')},
                {value: 'ISNULL', label: this.i18n('btnPreConf.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('btnPreConf.notEmpty', '不为空')},
            ],
            dateOptions: [
                {value: 'EQ', label: this.i18n('btnPreConf.equal', '等于')},
                {value: 'LT', label: this.i18n('btnPreConf.lessThan', '小于')},
                {value: 'GT', label: this.i18n('btnPreConf.greater', '大于')},
                {value: 'ISNULL', label: this.i18n('btnPreConf.isEmpty', '为空')},
                {value: 'NOTNULL', label: this.i18n('btnPreConf.notEmpty', '不为空')},
            ],
            easyCondition:{
                condition:"AND",
                rules:[],
            },
            defaultRule:{
                formField:undefined,
                op:"EQ",
                conditionConfig:"",
                dataType:"",
                valid:false,
                validMessage:'字段不能为空'
            },
        }
    },
    created() {
        this.init();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formBoList", key);
        },
        init() {
            if (this.config) {
                var json = JSON.parse(this.config);
                this.mode = json.mode;
                this.validMsg = json.validMsg;
                if (this.mode == 'easy') {
                    this.easyCondition = json.easyCondition;
                } else if (this.mode == 'hard') {
                    this.javaCode = json.javaCode;
                }
            }

            if (this.pkId) {
                FormBoListApi.reloadColumns(this.pkId).then(res => {
                    this.formFields = res.data.map(item => {
                        return {label: item.header, value: item.field,dataType: item.dataType};
                    })

                    let fields = res.data.map(item => {
                        return {title: item.header, key: item.field, isField: true};
                    });

                    this.boData.push({
                        key: 'formJson',
                        name: 'row',
                        title: this.i18n('formDialog.formField', '表单字段'),
                        isField: false,
                        children: fields
                    });

                });
            } else if (this.fieldDatas) {
                this.formFields = this.fieldDatas.map(item => {
                    return {label: item.comment, value: item.name, dataType: item.dataType};
                })

                let fields = this.fieldDatas.map(item => {
                    return {title: item.comment, key: item.name, isField: true};
                });

                this.boData.push({
                    key: 'formJson',
                    name: 'row',
                    title: this.i18n('formDialog.formField', '表单字段'),
                    isField: false,
                    children: fields
                });
            }
        },
        handleSubmit(vm) {
            if(this.mode == 'easy'){
                let data = this.$refs.easyCondition.getData();
                //验证不通过 允许为空
                if(data.rules.length>0 && !data.valid){
                    vm.loading = false;
                    this.$message.warning("验证不通过！");
                    return "";
                }
            }
            Util.closeWindow(this, "ok", this.getData());
        },
        cancel() {
            Util.closeWindow(this, "cancel");
        },
        insertConst(val) {
            this.$refs.javaCode.insertContent(val);
        },
        insertValidMsgCode(text) {
            this.$refs.validMsg.insertContent(text);
        },
        insertMsgConst(val) {
            this.$refs.validMsg.insertContent(val);
        },
        getData() {
            var obj = {mode: this.mode, validMsg: this.validMsg};
            if (this.mode == 'easy') {
                obj.easyCondition = this.$refs.easyCondition.getValue();
            } else if (this.mode == 'hard') {
                obj.javaCode = this.javaCode;
            }
            return JSON.stringify(obj);
        },
        showScriptDialog() {
            let self = this;
            let config = {curVm: this};
            Dialog.openScriptDialog(config, function (script) {
                self.$refs.javaCode.insertContent(script);
            })
        },
        formFieldChange(value, rule,setValid) {
            if (!value) {
                setValid(rule, false, '字段不能为空!');
                return;
            } else {
                setValid(rule, true);
            }
            for (var i = 0; i < this.formFields.length; i++) {
                if (value == this.formFields[i].value) {
                    rule.dataType = this.formFields[i].dataType;
                }
            }
            this.$set(rule,"conditionConfig","");
            this.$set(rule,"op",undefined);
        },
        selectBoNode(selKeys, e) {
            let node = e.node.dataRef;
            let isField = node.isField;

            if (!isField) {
                return;
            }
            let parentNode = e.node.$parent.dataRef;
            this.insertJavaCode(parentNode.name + "." + node.key);

        },
        insertJavaCode(text) {
            this.$refs.javaCode.insertContent(text);
        },
        change() {
          this.$forceUpdate()
        },
        insertFor(ctl) {
            let code = `import com.alibaba.fastjson.JSONObject;
for(int i=0;i<rows.size();i++){
   JSONObject  row=rows[i];
}
return true;
`;
            this.$refs[ctl].insertContent(code);
        },
        insertSingle(ctl) {
            let code = `import com.alibaba.fastjson.JSONObject;
JSONObject row=rows[0];
return true;
`;
            this.$refs[ctl].insertContent(code);
        }
    }
}
</script>

<style scoped>
.form-tree-certen {
  position: relative;
}

.form-tree-certen:hover .form-tree {
  display: block;
}

.form-tree {
  position: absolute;
  top: 44px;
  display: none;
  left: 0px;
  min-width: 170px;
  max-height: 300px;
  overflow: auto;
  z-index: 1000;
  background-color: #ffffff;
  border-radius: 4px;
  border: solid 1px #e3e3e3;
}

.FormSolutionDefMappingConfig-easy {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.rx-monaco-editor-center {
  flex: 1;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
}

.formSolution {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.addbutton {
  margin-bottom: 15px;
}

.formSolution-center {
  height: 100%;
  display: flex;
  flex: 1;
}

.formSolution-center-flex {
  flex-direction: column;
}

.findSelectBox {
  flex: 1;
  margin-right: 20px;
}

.findInputBox {
  flex: 2;
}
</style>